package com.macro.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.ResultCode;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.mapper.MbrMemberScoreMapper;
import com.macro.mall.model.*;
import com.macro.mall.service.CommonService;
import com.macro.mall.service.MbrMemberScoreService;
import com.macro.mall.utils.Mapping;
import com.macro.mall.vo.TagStatistics;
import com.macro.mall.vo.TrainingAvgStatistics;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * MbrMemberScore的服务接口的实现类
 * 
 * @author gaodx
 *
 */
@Slf4j
@Service
public class MbrMemberScoreServiceImpl implements MbrMemberScoreService {

    private boolean isDebugEnabled = true;

	@Autowired
	private CommonService commonService;
	@Autowired
	private MbrMemberScoreMapper mbrMemberScoreMapper;
	// TODO 当你看到这个方法时你应该创建一个工具类做通用的方法,定义自己的返回格式化

	@Override
	public List<MbrMemberScore> find(MbrMemberScore value) {
		//TODO这里可以做通过Assist做添加查询
		List<MbrMemberScore> result = mbrMemberScoreMapper.selectMbrMemberScore(null);
		if (isDebugEnabled) {
			log.debug("执行获取MbrMemberScore数据集-->结果:", result);
		}
		return result;
	}
	@Override
	public MbrMemberScore findOne(Long id) {
		if (id == null) {
			if (isDebugEnabled) {
				log.debug("执行通过MbrMemberScore的id获得MbrMemberScore对象-->失败:id不能为空");
			}
            Asserts.fail("执行通过MbrMemberScore的id获得MbrMemberScore对象-->失败:id不能为空");
		}
		MbrMemberScore result = mbrMemberScoreMapper.selectMbrMemberScoreById(id);
		if (isDebugEnabled) {
			log.debug("执行通过MbrMemberScore的id获得MbrMemberScore对象-->结果:", result);
		}
		return result;
	}

	@Override
	public CommonResult saveNotNull(MbrMemberScore value) {
		if (value == null) {
			if (isDebugEnabled) {
				log.debug("执行将MbrMemberScore中属性值不为null的数据保存到数据库-->失败:对象不能为空");
			}
                Asserts.fail("失败:对象不能为空");
		}
		int result = mbrMemberScoreMapper.insertNotNullMbrMemberScore(value);
		if (isDebugEnabled) {
			log.debug("执行将MbrMemberScore中属性值不为null的数据保存到数据库-->结果:", result);
		}
            return CommonResult.success(null);
	}
	@Override
	public CommonResult updateNotNullById(MbrMemberScore value) {
		if (value == null) {
			if (isDebugEnabled) {
				log.debug("执行通过MbrMemberScore的id更新MbrMemberScore中属性不为null的数据-->失败:对象为null");
			}
                Asserts.fail("执行通过MbrMemberScore的id更新MbrMemberScore中属性不为null的数据-->失败:对象为null");
		}
		int result = mbrMemberScoreMapper.updateNotNullMbrMemberScoreById(value);
		if (isDebugEnabled) {
			log.debug("执行通过MbrMemberScore的id更新MbrMemberScore中属性不为null的数据-->结果:", result);
		}
        return CommonResult.success(null);
	}

	@Override
	public CommonResult deleteById(Long id) {
		if (id == null) {
			if (isDebugEnabled) {
				log.debug("执行通过MbrMemberScore的id删除MbrMemberScore-->失败:id不能为空");
			}
                Asserts.fail("执行通过MbrMemberScore的id删除MbrMemberScore-->失败:id不能为空");
		}
		int result = mbrMemberScoreMapper.deleteMbrMemberScoreById(id);
		if (isDebugEnabled) {
			log.debug("执行通过MbrMemberScore的id删除MbrMemberScore-->结果:", result);
		}
        return CommonResult.success(null);
	}

    @Override
    public MbrMemberScore findOne(Integer targetType, String targetId) {
        MbrMemberScore build = MbrMemberScore.builder().targetType(targetType).targetId(targetId).build();

        MbrMemberScore result = mbrMemberScoreMapper.selectMbrMemberScoreObjSingle(build);
        if (isDebugEnabled) {
            log.debug("执行通过MbrMemberScore的id获得MbrMemberScore对象-->结果:", result);
        }
        return result;
    }

	@Override
	public TrainingAvgStatistics selectTrainingAvg(Integer trainingId) {
		TrainingAvgStatistics result = new TrainingAvgStatistics();
		Integer scoreAvg = mbrMemberScoreMapper.selectAvgScoreTrainingObjSingle(trainingId);
		result.setTrainingId(trainingId);
		result.setTrainingAvg(scoreAvg);
		if (isDebugEnabled) {
			log.debug("执行通过trainingId获得trainingId平均值-->结果:", result);
		}
		return result;
	}

	@Override
	public List<MbrMemberScoreStatistics> findAll(String username, String phone, Integer targetType, String communityName, String courseName, Integer pageNum, Integer pageSize) {
		List<MbrMemberScoreStatistics> result = null;
		try {
			PageHelper.startPage(pageNum, pageSize);
			result = mbrMemberScoreMapper.selectMbrMemberScoreStatistics(username,phone,targetType,communityName,courseName);
			result.stream().forEach(r->{
				r.setUserIdentityName(Mapping.getSplitName(r.getUserIdentity()));
				r.setTargetName(Mapping.targetTypeMap.get(r.getTargetType().toString()));
			});
		} catch (Exception e) {
			log.error("", e);
			Asserts.fail(ResultCode.FAILED);
		}
		if (isDebugEnabled) {
			log.debug("执行获取MbrMemberScoreStatistics数据集-->结果:{}", result);
		}
		return result;
	}

	@Override
	public List<TagStatistics> scoreMax(String commonType, Integer trainingId, Integer courseId, Integer num) {
		List<TagStatistics> sumScore = new ArrayList<>();
		List<TagStatistics> result = null;
		Common common = new Common();
		common.setCommonType(commonType);
		List<Common> commons = commonService.find(common);
		commons.stream().forEach(cm->{
			Integer total = mbrMemberScoreMapper.selectScoreMax(cm.getId(),trainingId,courseId);
			if (total!=null) {
				TagStatistics tagStatistics = new TagStatistics();
				tagStatistics.setTrainingId(trainingId);
				tagStatistics.setCourseId(courseId);
				tagStatistics.setTagId(cm.getId());
				tagStatistics.setLabel(cm.getCommonDesc());
				tagStatistics.setTotal(total);
				sumScore.add(tagStatistics);
			}
		});
		if (!CollectionUtils.isEmpty(sumScore)) {
			result = sumScore.stream().sorted(Comparator.comparing(TagStatistics::getTotal, Comparator.reverseOrder())).limit(num).collect(Collectors.toList());
		}
		if (isDebugEnabled) {
			log.debug("执行获取TagStatistics数据集-->结果:{}", result);
		}
		return result;
	}

	@Override
	public void exportExcelScore(HttpServletResponse response, String title, String[] headers, List<MbrMemberScoreStatistics> list, List<String> listColumn) {
		HSSFWorkbook workbook = null;
		try {
			workbook = new HSSFWorkbook();
			HSSFSheet sheet = workbook.createSheet();
			workbook.setSheetName(0, title);
			HSSFRow row = sheet.createRow(0);
			/*创建第一行表头*/
			for (short i = 0; i < headers.length; i++) {
				HSSFCell cell = row.createCell(i);
				HSSFRichTextString text = new HSSFRichTextString(headers[i]);
				cell.setCellValue(text);
				HSSFCellStyle style = workbook.createCellStyle();
				Font font = workbook.createFont();
				font.setFontName("Arial");
				style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
				style.setFont(font);
				cell.setCellStyle(style);
			}
			int index = 1;
			for(MbrMemberScoreStatistics t : list){
				row = sheet.createRow(index);
				row.createCell(0).setCellValue(t.getName());
				row.createCell(1).setCellValue(t.getPhone());
				row.createCell(2).setCellValue(t.getCommunityName());
				row.createCell(3).setCellValue(t.getUserIdentityName());
				row.createCell(4).setCellValue(t.getTrainingName());
				row.createCell(5).setCellValue(t.getCourseName());
				row.createCell(6).setCellValue(t.getTargetName());
				row.createCell(7).setCellValue(t.getScore());
				row.createCell(8).setCellValue(t.getLabel());
				row.createCell(9).setCellValue(t.getCommentContent());
				HSSFCell cell10 = row.createCell(10);
				cell10.setCellValue(t.getCreateTime());
				HSSFDataFormat dataFormat = workbook.createDataFormat();
				HSSFCellStyle style = workbook.createCellStyle();
				style.setDataFormat(dataFormat.getFormat("yyyy-MM-dd hh:mm:ss"));
				cell10.setCellStyle(style);
				index++;
			}
            /*application/vnd.ms-excel告诉浏览器要下载的是个excel*/
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            /*请求头设置，Content-Disposition为下载标识，attachment标识以附件方式下载*/
            response.addHeader( "Content-Disposition", "attachment;filename=" + new String((title).getBytes(), "ISO8859-1" ) + ".xls");
			workbook.write(response.getOutputStream());
		}catch (Exception e ){
			e.printStackTrace();
			log.error(e.getMessage());
		}
//        } finally {
//            if (workbook != null) {
////                workbook.close();
//            }
//        }
	}

}